package com.webmall.filter;
/**
 * 管理后台登陆的拦截器
 * 代改 注解 还有具体实现
 * 还有要被拦截验证的那几个servlet的注解
 */

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebFilter("/manageHtml/*")
public class AdminLogin implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //1.需要将servletRequest转换到父类
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)resp;

        //2.字符集
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");

        HttpSession session = request.getSession();
        String adminStatus = (String) session.getAttribute("isAdmin");

        String request_uri = request.getRequestURI();
        System.out.println(request_uri+"%%%%"+request.getContextPath());///manage/admin_doUserShow
        if (request_uri.contains("admin_")){

            if (null != adminStatus && adminStatus.equals("1")){//是管理员登录的

                chain.doFilter(request, response);
            }else {
                PrintWriter out = response.getWriter();
                out.write("<script>");
                out.write("alert('只有管理员登录才可以');");
                out.write("location.href='/manageHtml/adminLogin.jsp';");
                out.write("</script>");
                out.close();
                return;
            }
        }else{
            chain.doFilter(request, response);
        }

//
        return;
       //
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
